package com.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.persistence.TFootballTeam;
import com.persistence.TPlayer;
import com.service.PlayerService;
import com.service.TeamService;

@Controller
@SessionAttributes
public class CaptainAddController extends AbstractController {
	ApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"applicationContext.xml"});
	TeamService teamDao = (TeamService) context.getBean("teamService");
	PlayerService playerDao = (PlayerService) context.getBean("playerService");
	
	@Override
	@RequestMapping(value = "/saveCaptain", method = RequestMethod.POST)
	protected ModelAndView handleRequestInternal(HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		
		String teamId = req.getParameter("teamId");
		String playerId = req.getParameter("playerId");
		
		TFootballTeam team = teamDao.findById(Integer.parseInt(teamId));
		List<TPlayer> list = team.getCaptains();
		TPlayer player = playerDao.findById(Integer.parseInt(playerId));
		list.add(player);
		team.setCaptains(list);
		teamDao.update(team);
		
		List<TFootballTeam> list2 = teamDao.findAll();
		TFootballTeam team2 = teamDao.findById(Integer.parseInt(teamId));
		Map<String, Object> list3 = new HashMap<String, Object>();
		List<TPlayer> list4 = team.getCaptains();

		list3.put("team", list2);
		list3.put("player", list4);
		list3.put("team2", team2);

		req.setAttribute("list3",list3);
		res.sendRedirect("main.htm?module=captain&action=view&teamid=" + teamId);
		return new ModelAndView("showCaptain", "list3", list3);

	}

}
